// UI元素
const settingsBtn = document.getElementById('settings-btn');
const settings = document.getElementById('settings');
const settingsForm = document.getElementById('settings-form');
const difficultySelect = document.getElementById('difficulty');
const wordDisplay = document.getElementById('word');
const textInput = document.getElementById('text');
const scoreDisplay = document.getElementById('score');
const timeDisplay = document.getElementById('time');
const endGameContainer = document.getElementById('end-game-container');
const finalScoreDisplay = document.getElementById('final-score');

// 单词列表
const words = [
    'const',
    'let',
    'input',
    'image',
    'form',
    'style',
    'display',
    'container',
    'element',
    'class',
    'document',
    'background',
    'transition',
    'transform',
    'translate',
    'border',
    'radius',
    'margin',
    'padding',
    'select'
];

// 游戏变量
let randomWord;
let score = 0;
let time = 10;
let difficulty = localStorage.getItem('difficulty') !== null ? 
    localStorage.getItem('difficulty') : 'medium';
let timer;

// 初始化难度选择
difficultySelect.value = difficulty;

// 聚焦输入框
textInput.focus();

// 生成随机单词
function getRandomWord() {
    return words[Math.floor(Math.random() * words.length)];
}

// 添加单词到DOM
function addWordToDOM() {
    randomWord = getRandomWord();
    wordDisplay.innerHTML = randomWord;
}

// 更新分数
function updateScore() {
    score++;
    scoreDisplay.innerHTML = score;
}

// 更新剩余时间
function updateTime() {
    time--;
    timeDisplay.innerHTML = time;

    if (time === 0) {
        clearInterval(timer);
        gameOver();
    }
}

// 游戏结束
function gameOver() {
    endGameContainer.style.display = 'flex';
    finalScoreDisplay.innerHTML = score;
}

// 事件监听器

// 输入事件
textInput.addEventListener('input', e => {
    const typedText = e.target.value;

    if (typedText === randomWord) {
        addWordToDOM();
        updateScore();
        e.target.value = '';

        // 根据难度增加时间
        if (difficulty === 'hard') {
            time += 2;
        } else if (difficulty === 'medium') {
            time += 3;
        } else {
            time += 5;
        }

        timeDisplay.innerHTML = time;
    }
});

// 设置按钮点击事件
settingsBtn.addEventListener('click', () => {
    settings.classList.toggle('hide');
});

// 难度选择变化事件
difficultySelect.addEventListener('change', e => {
    difficulty = e.target.value;
    localStorage.setItem('difficulty', difficulty);
});

// 初始化游戏
function init() {
    addWordToDOM();
    timer = setInterval(updateTime, 1000);
}

init();